package wqh.global;


import java.util.HashMap;
import java.util.Map;

public  class GlobalSession {

    private static final Map<String,String> sessionIdMap = new HashMap<String, String>();

    public static  synchronized void addSession(String userName, String sessionID)
    {
        sessionIdMap.put(userName,sessionID);
    }

    public static synchronized void removeSessionByName(String userName)
    {
        sessionIdMap.remove(userName);
    }

    public static synchronized void removeSessionBySessionID(String sessionID)
    {
        for(Map.Entry<String,String> map : sessionIdMap.entrySet())
        {
            if(map.getValue().equals(sessionID))
            {
                sessionIdMap.remove(map.getKey());
                break;
            }
        }
    }

    public static synchronized String removeSessionBySessionIDGetName(String sessionID)
    {
        String name = null;
        for(Map.Entry<String,String> map : sessionIdMap.entrySet())
        {
            if(map.getValue().equals(sessionID))
            {
                name = map.getKey();
                sessionIdMap.remove(map.getKey());
            }
        }
        return name;
    }

    public static synchronized String getUserNameBySessionID(String sessionID){
        for(Map.Entry<String,String> map : sessionIdMap.entrySet())
        {
            if(map.getValue().equals(sessionID))
            {
                return map.getKey();
            }
        }
        return null;
    }

    public static synchronized boolean existSessionID(String sessionID)
    {
        for(Map.Entry<String,String> map : sessionIdMap.entrySet())
        {
            if(map.getValue().equals(sessionID))
            {
                return true;
            }
        }
        return false;
    }

    public static Map<String, String> getSessionIdMap() {
        return sessionIdMap;
    }
}
